// pages/usercenter/staff/deliveryFee/deliFee.js
import {
  ui
} from '../../../../tools/ui';
import {
  users
} from '../../../../tools/users'
import {
  ds
} from '../../../../tools/data'
import {
  dateTool
} from '../../../../tools/date'
import {
  adv
} from '../../../../tools/adv'

Page({
  data: {
    staff: {},
    pickerIndexList: [0, 0, 0], //日期选择器下标
    isShowDateLayer: false, //是否显示日期弹层
    txtDate: '请选择日期', //选中日期
    isSeltDate: false, //是否选择日期
    globalData: {},
    date: {},
    loading: true,
    curDate: null,
    readOnly: true,
  },
  onLoad(options) {
    // console.log(options)
    const that = this;
    const {
      nickName,
      staffId
    } = options
    const title = nickName + '的提成'
    wx.setNavigationBarTitle({
      title
    })
    this.setData({
      title
    })
    this.init(staffId)
    this.loadUser()

  },
  init(staffId) {
    const curDate = new Date().getTime()
    this.setData({
      curDate,
      date: {
        end: curDate
      }
    })
    this.loadStaff(staffId)
  },
  loadUser() {
    users.getUserInfo()
      .then(u => {
        this.setData({
          readOnly: u.role != 'admin'
        })
      })
  },

  loadStaff(staffId) {
    ds.coll('users')
      .where({
        _id: staffId
      })
      .get()
      .then(async res => {
        const staff = res.data[0]
        // console.log(staff)

        const feeRes = await adv.calcDeductFee(staff)
        this.setData({
          staff,
          date: {
            start: feeRes.startTime,
            end: feeRes.endTime
          },
          fee: feeRes.fee.toFixed(2)
        })
        ui.loading(false)
        // console.log(feeRes)
        // this.loadOrders(staff)
      })
  },
  // async loadOrders(staff) { -> tools/adv.js
  //   // 绑定的用户
  //   const userRes = await ds.coll('users')
  //     .where({
  //       bind: staff._openid
  //     })
  //     .get()
  //   const bindUsers = userRes.data
  //   const deductFee = staff.deductFee
  //   // console.log('bind users', bindUsers)

  //   // 这些用户的订单
  //   const _ = ds.cmd
  //   const startTime = this.calcStartTime(deductFee), // deductFee是结算历史记录
  //     endTime = this.data.curDate
  //   const userOpenids = bindUsers.map(ele => ele._openid)
  //   // console.log('user openids', userOpenids)
  //   // console.log('startTime', startTime)
  //   const orders = await ds.getAll('orders', {
  //     _openid: _.in(userOpenids),
  //     status: '已送达',
  //     createTime: _.and(startTime ? _.gt(startTime) : {}, _.lte(endTime))
  //   })
  //   // console.log('orders', orders)

  //   this.calcFee(orders)
  // },
  // calcFee(orders) {
  //   let startTime = false,
  //     totalFee = 0
  //   orders.forEach(anOrder => {
  //     startTime = (startTime ? Math.min(startTime, anOrder.createTime) : anOrder.createTime)
  //     let goodsMap = {}
  //     anOrder.goodsSnap.forEach(aSnap => {
  //       goodsMap[aSnap._id] = aSnap
  //     })
  //     anOrder.goodsList.forEach(aGoods => {
  //       const {
  //         num,
  //         price
  //       } = aGoods
  //       const deduct = Number(goodsMap[aGoods.spuId].deduct)
  //       // console.log('deduct', deduct)
  //       let fee = 0
  //       if (deduct >= 1) fee = Number(num) * (deduct)
  //       else if (deduct < 1) fee = Number(num) * Number(price) * (deduct)
  //       totalFee += fee
  //     })
  //   })
  //   // console.log('total fee', totalFee)

  //   const date = this.data.date
  //   if (!date.start && startTime) {
  //     date.start = startTime
  //     this.setData({
  //       date
  //     })
  //   }

  //   this.setData({
  //     fee: totalFee.toFixed(2)
  //   })
  //   ui.loading(false)
  // },
  // calcStartTime(deductFee) { // 上次结算的终止时间，作为本次结算的起始时间
  //   let start = false;
  //   (deductFee || []).forEach(obj => {
  //     start = (start ? Math.max(obj.end, start) : obj.end)
  //   })

  //   // console.log('start', start)
  //   if (start) {
  //     const date = this.data.date
  //     date.start = start
  //     this.setData({
  //       date
  //     })
  //   }
  //   return start
  // },
  onSettleTap() {
    const {
      staff,
      date,
      fee
    } = this.data
    ui.confirm('确定结算吗？', async res => {
      if (!res) return

      ui.loading()
      const resSettle = await adv.settleDeductFee(staff, {
        startTime: date.start,
        endTime: date.end,
        fee
      })
      ui.loading(false)
      if (resSettle.success) this.init(staff._id)
      else ui.toast(resSettle.success, resSettle.msg)
    })
  },
  // async onSettleTap() { // 结算 -> tools/adv.js
  //   const date = this.data.date
  //   if (!date.start || !date.end) return
  //   // console.log(date)
  //   if (date.start > date.end) {
  //     ui.toast(false, '日期区间错误')
  //     return
  //   }

  //   const doSettle = () => {
  //     // 去除重复
  //     ui.loading()
  //     const staff = this.data.staff
  //     const deductFee = (staff.deductFee || [])
  //     const found = deductFee.find(ele => (ele.start == date.start && ele.end == date.end))
  //     if (found) {
  //       ui.loading(false)
  //       return
  //     }

  //     deductFee.push({
  //       start: date.start,
  //       end: date.end,
  //       fee: this.data.fee,
  //     })
  //     // console.log('deliveryFee', deliveryFee, staff._id)

  //     // 更新
  //     ds.cloudUpdate('users', staff._id, {
  //       deductFee
  //     }, res => {
  //       this.init(staff._id)
  //     })
  //   }

  //   ui.confirm('确定结算吗？', res => {
  //     if (!res) return
  //     doSettle()
  //   })
  // },

  onShow() {
    if (this.data.loading) ui.loading()
  },
})